import { defineStore } from 'pinia';
import { APP_TOKEN, WEB_HTTP_AUTH_HEADER } from '@/constants';
import { Storage } from '@/utils/Storage';
import type { UserStoreType } from '../types';
import UserService from '@/api/user';
import { AppUser } from '@/@types';

const useUserStore = defineStore('user', {
  state: (): UserStoreType => ({
    token: Storage.get(APP_TOKEN, '') as string,
    tokenHeader: Storage.get(WEB_HTTP_AUTH_HEADER, 'Authorization-Hr'),
    userDetail: null,
  }),
  getters: {
    hasUserInfo: (state: UserStoreType): boolean => !!state?.userDetail?.mobile,
  },
  actions: {
    setToken(value: string | undefined) {
      Storage.set(APP_TOKEN, value);
      this.token = value!;
    },
    setTokenHeader(value: string | undefined) {
      Storage.set(WEB_HTTP_AUTH_HEADER, value);
      this.tokenHeader = value!;
    },

    setUserInfo(info: AppUser) {
      this.userDetail = info;
    },

    async getUserDetail() {
      const resp = await UserService.getUserDetail<AppUser>();
      if (resp.code === 200) {
        this.userDetail = resp.data!;
        return true;
      }
      return false;
    },

    async appLogout() {
      await UserService.logout(0);
      this.setToken('');
      Storage.clear();
    },
  },
});

export { useUserStore };
